package com.hxkj.lts.aop;


import com.hxkj.lts.context.Page;
import com.hxkj.lts.context.PagingContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by chenwei on 2018/11/21.
 */
@Aspect
@Service("mongoPagingAdvices")
@Slf4j
public class MongoPagingAdvices {

    @Pointcut("execution (* org.springframework.data.mongodb.core.MongoTemplate.find(..))")
    public void pointCut() {

    }

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        MongoTemplate mongoTemplate = (MongoTemplate) joinPoint.getThis();
        // 翻页参数
        Page page = PagingContextHolder.getPage();
        if (page != null) {
            Object[] args = joinPoint.getArgs();
            Query query = (Query) args[0];

            long count = mongoTemplate.count(query, (Class) args[1]);
            page.setTotalResult(count);
            if (log.isDebugEnabled()) {
                log.debug(String.valueOf(count));
            }
            query.limit((int) page.getPageSize());
            query.skip((int) (page.getCurrentPage() * page.getPageSize()));
            args[0] = query;
        }

    }

    @AfterReturning(pointcut = "pointCut()", returning = "returnValue")
    public void after(Object returnValue) {
        Page page = PagingContextHolder.getPage();
        if (page != null && returnValue instanceof List) {
            page.setData((List) returnValue);
        }
    }

}
